package com.wgj.android.accesslibility.job;

import android.accessibilityservice.AccessibilityService;
import android.app.Notification;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.ListView;
import android.widget.TextView;

import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.utils.XDateUtils;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.accesslibility.AccessibilityHelper;
import com.wgj.android.accesslibility.IStatusBarNotification;
import com.wgj.android.utils.NotifyHelper;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/11/11.
 */

public class WXAShareJob implements AccessbilityJob {
    private AccessibilityService service;
    private static  final   String  TAG="WXShare";
    private  static  final  String MANY_SHARE_CACHE_KEY="_many_share_cache_key"; //高级分享绶存标识
    private  static  final  String SHARE_CACHE_KEY="share_cache_key"; //普通分享绶存标识
    private  static  final  String checkBoxId="com.tencent.mm:id/pt"; //联系人列表单选按钮
    private  static  final  String CONTACT_ITEM_ID="com.tencent.mm:id/c55"; //联系人
    private  static AccessibilityNodeInfo listView=null; //联系人列表
    private  static  int selectIndex=0; //当前已选择的人数
    private static   boolean isNotMore=false; //是否已到底部的标识


    private static HashSet<String> shareSelects=new HashSet<>(); //当前已选中的联系人昵称集合





    private boolean isEnable=true;


    private  static  int indexOf=0;

    @Override
    public String getTargetPackageName() {
        return "com.tencent.mm";
    }

    @Override
    public void onCreateJob(AccessibilityService service) {
        this.service=service;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onReceiveJob(AccessibilityEvent event) {

        AccessibilityNodeInfo rootNodeInfo=null;
        String className = event.getClassName().toString();
        switch (className){
            case "com.tencent.mm.ui.transmit.SelectConversationUI"://进入到分享页面
                 rootNodeInfo=service.getRootInActiveWindow();
                if(rootNodeInfo!=null){
                    selectIndex=0;
                    isNotMore=false;
                    AccessibilityHelper.performClick(AccessibilityHelper.findNodeInfosByText(rootNodeInfo,"创建新聊天"));
                }
                break;
            case "com.tencent.mm.ui.contact.SelectContactUI"://进入到分享选择联系人界面
                 selectContact(39);

                break;
            case "com.tencent.mm.ui.transmit.SendAppMessageWrapperUI":
                break;

        }

    }

    @Override
    public void onStopJob() {
          isEnable=false;
    }

    @Override
    public void onNotificationPosted(IStatusBarNotification event) {

    }

    @Override
    public void setWeiXingVersion(int version) {

    }


    @Override
    public boolean isEnable() {
        return isEnable;
    }




    /**
     * 选择联系人
     * @param size
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void  selectContact(int size){
        shareSelects=getShareCache();
        while (selectIndex!=size){
            AccessibilityNodeInfo nodeInfo=getNextConiact();
            if(nodeInfo!=null){
                AccessibilityHelper.performClick(nodeInfo);
                selectIndex+=1;
            }else {
                selectIndex=0;
                continue;
            }
        }
        saveShareCache();
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  AccessibilityNodeInfo  getNextConiact(){
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        AccessibilityNodeInfo rootNodeInfo=service.getRootInActiveWindow();
            if(rootNodeInfo!=null) {
                AccessibilityNodeInfo listView = AccessibilityHelper.findNodeInfosByClassName(rootNodeInfo, AccessibilityHelper.LIST_VIEW_CLASS_NAME);
                List<AccessibilityNodeInfo> items = listView.findAccessibilityNodeInfosByViewId(CONTACT_ITEM_ID);
                for (int i = 0; i < items.size(); i++) {
                    AccessibilityNodeInfo nickNode = AccessibilityHelper.findNodeInfosByClassName(items.get(i), TextView.class.getName());
                    if (nickNode != null) {
                        if (!shareSelects.contains(nickNode.getText().toString())) {
                            shareSelects.add(nickNode.getText().toString());
                            return items.get(i);
                        }
                    }
                }
                if(listView.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)){
                    return  getNextConiact();
                }else{
                    return null;
                }
            }else{
                return  null;
            }


    }

    /**
     * 获取已选中的人
     * @return
     */
    private HashSet<String>  getManyShareCache(){
        String  cachkey= XDateUtils.format(new Date(),"yyyyMMdd")+MANY_SHARE_CACHE_KEY;
        HashSet<String>  s= (HashSet<String>) XCache.get(getContext()).getAsObject(cachkey);
        if(s==null){
            s=new HashSet<>();
        }
        return s;
    }
    /**
     * 获取已选中的人
     * @return
     */
    private HashSet<String>  getShareCache(){
        String  cachkey= XDateUtils.format(new Date(),"yyyyMMdd")+SHARE_CACHE_KEY;
        HashSet<String>  s= (HashSet<String>) XCache.get(getContext()).getAsObject(cachkey);
        if(s==null){
            s=new HashSet<>();
        }
        return s;
    }
    /**
     * 获取已选中的人
     * @return
     */
    private void   saveShareCache(){
        String  cachkey= XDateUtils.format(new Date(),"yyyyMMdd")+SHARE_CACHE_KEY;
        XCache.get(getContext()).put(cachkey,shareSelects);
     }

    /**
     * 打开群发界面
     */
    private  void  openMessagePluginsUi(){
        AccessibilityNodeInfo rootNodeInfo=service.getRootInActiveWindow();
        if(rootNodeInfo!=null){
            AccessibilityNodeInfo nodes = AccessibilityHelper.findNodeInfosByText(rootNodeInfo,"群发助手");
            if(nodes!=null){
                AccessibilityHelper.performClick(nodes);
            }
        }
    }

    public ArrayList<HashMap<String, Object>> getItems(Context context) {

        PackageManager pckMan = context.getPackageManager();
        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();

        List<PackageInfo> packageInfo = pckMan.getInstalledPackages(0);

        for (PackageInfo pInfo : packageInfo) {

            HashMap<String, Object> item = new HashMap<String, Object>();

            item.put("appimage", pInfo.applicationInfo.loadIcon(pckMan));
            item.put("packageName", pInfo.packageName);
            item.put("versionCode", pInfo.versionCode);
            item.put("versionName", pInfo.versionName);
            item.put("appName", pInfo.applicationInfo.loadLabel(pckMan).toString());

            items.add(item);

        }

        return items;
    }

    private Context getContext(){
        return  service.getApplicationContext();
    }

}
